package basic;

import misc.Util;
	
	/*
	 * 	this class represents the key generated. it consists of number of sequences
	 * 	selected at key generation.
	 * 	
	 * @author Dusan Guduric
	 */
public class Key {
	/* array of sequences that represent the key generated*/
	private Sequence[] sequence =  null;
	/* default constructor for key class*/
	public Key() {
		this.sequence = null;
	}
	/* constructor that makes the key from sequences provided
	 * @param sequences array of sequences provided for key
	 * */
	public Key(Sequence[] sequences) {
		this.sequence = sequences;
	}
	/* construtor that makes key with number of empty sequences
	 * @param number generates key for provided number of empty sequences
	 * */
	public Key(int number){
		this.sequence = new Sequence[number];
	}

	public Sequence addSequence(String sequence){
		return new Sequence(sequence, getSequenceSum(sequence));
	}
	
	public Sequence addSequenceAt(String sequence, int n){
		if (sequence == null)
			return null;
		return this.sequence[n] = new Sequence(sequence, getSequenceSum(sequence));
	}

	private int getSequenceSum(String sequence){
		int sum = 0;
		for (int i = 0; i < sequence.length(); i++){
			char c = sequence.charAt(i);
			if (Character.isLetter(c)){
				sum = sum + Util.convertCharToInt(c);
			} else {
				sum = sum + Integer.parseInt(Character.toString(c));
			}
		}
		return sum;
	}
	public Sequence getSequenceAt(int index){
		return this.sequence[index];
	}
	
	public Sequence[] getSequences() {
		return sequence;
	}
	public void setSequences(Sequence[] sequence) {
		this.sequence = sequence;
	}
	public boolean isFirstGenerated(){
		try {
		if (this.sequence[0] != null)
			return true;
		} catch (NullPointerException e) {
			return false;
		}
		return false;
	}
	public boolean isGenerated(int n){
		try {
		if (this.sequence[n] != null)
			return true;
		} catch (NullPointerException e) {
			return false;
		}
		return false;
	}
	public boolean isLastGenerated(){
		try {
		if (this.sequence[sequence.length-1] != null)
			return true;
		} catch (NullPointerException e) {
			return false;
		}
		return false;
	}

	public String getKey(){
		String key = "";
		for (int i = 0; i < sequence.length; i++){
			if (sequence[i] != null)
				key = key + sequence[i].getSequence() +"-";
			else
				key = key + " " + "-";
		}
		return key.substring(0, key.length()-1);
	}

}
